//
//  Util.m
//  LimeWireStore
//
//  Created by Jeffrey Palm on 12/14/08.
//  Copyright 2008 Navtones. All rights reserved.
//

#import "Util.h"

@implementation Util

+ (NSString*)findStringInBetweenThrowing:(NSString*)s start:(NSString*)startDelim end:(NSString*)endDelim {
	NSRange istart = [s rangeOfString:startDelim];
	if (istart.location >= 0) {
		NSUInteger loc = istart.location + istart.length + 1;
		NSUInteger len = [s length] - loc - 1;
		NSRange istop = [s rangeOfString:endDelim options:NSCaseInsensitiveSearch range:NSMakeRange(loc,len)];
		if (istop.location > istart.location) {
			NSString *res = [s substringWithRange:NSMakeRange(istart.location + istart.length, 
																istop.location-istart.location - istart.length)];
			return res;
		}
	}
	return nil;
}

+ (NSString*)findStringInBetween:(NSString*)s start:(NSString*)startDelim end:(NSString*)endDelim {
		@try {
			return [self findStringInBetweenThrowing:s start:startDelim end:endDelim];
		}
		@catch (NSException * e) {

		}
		@finally {

		}
	return nil;
}

+ (NSString*)unescapeHTML:(NSString*)html {
	NSString *res = html;
	res = [res stringByReplacingOccurrencesOfString:@"&amp;"	withString:@"&"];
	res = [res stringByReplacingOccurrencesOfString:@"&lt;"		withString:@"<"];
	res = [res stringByReplacingOccurrencesOfString:@"&gt;"		withString:@">"];
	res = [res stringByReplacingOccurrencesOfString:@"\\'"		withString:@"'"];
	res = [res stringByReplacingOccurrencesOfString:@"\\\""		withString:@"\""];
	return res;
}

/*
 this function was taken from an XML example
 provided by Apple
 
 I can take no credit in this
 */
+ (UILabel *)newLabelWithPrimaryColor:(UIColor *)primaryColor selectedColor:(UIColor *)selectedColor fontSize:(CGFloat)fontSize bold:(BOOL)bold {
	/*
	 Create and configure a label.
	 */
	
	UIFont *font;
	if (bold) {
		font = [UIFont boldSystemFontOfSize:fontSize];
	} else {
		font = [UIFont systemFontOfSize:fontSize];
	}
	
	/*
	 Views are drawn most efficiently when they are opaque and do not have a clear background, so set these defaults.  To show selection properly, however, the views need to be transparent (so that the selection color shows through).  This is handled in setSelected:animated:.
	 */
	UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectZero];
	newLabel.backgroundColor = [UIColor whiteColor];
	newLabel.opaque = YES;
	newLabel.textColor = primaryColor;
	newLabel.highlightedTextColor = selectedColor;
	newLabel.font = font;
	
	return newLabel;
}

+ (CGRect)imageBounds:(UIImage*)image x:(NSInteger)theX y:(NSInteger)theY {
	CGImageRef imgRef = image.CGImage;  
	CGFloat width = CGImageGetWidth(imgRef);  
	CGFloat height = CGImageGetHeight(imgRef);  	
	return CGRectMake(theX, theY, width, height);
}


/*
 * http://blog.logichigh.com/2008/06/05/uiimage-fix/
 */
+ (UIImage*)scaleAndRotateImage:(UIImage*)image maxResolution:(int)theMaxResolution {
		
	CGImageRef imgRef = image.CGImage;  
	
	CGFloat width = CGImageGetWidth(imgRef);  
	CGFloat height = CGImageGetHeight(imgRef);  
	
	NSLog(@"scaleAndRotateImage max=%d width=%f height=%f", theMaxResolution, width, height);
	
	CGAffineTransform transform = CGAffineTransformIdentity;  
	CGRect bounds = CGRectMake(0, 0, width, height);  
	if (width > theMaxResolution || height > theMaxResolution) {  
		CGFloat ratio = width/height;  
		if (ratio > 1) {  
			bounds.size.width = theMaxResolution;  
			bounds.size.height = bounds.size.width / ratio;  
		}  
		else {  
			bounds.size.height = theMaxResolution;  
			bounds.size.width = bounds.size.height * ratio;  
		}  
	}  
	
	CGFloat scaleRatio = bounds.size.width / width;  
	CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));  
	CGFloat boundHeight;  
	UIImageOrientation orient = image.imageOrientation;  
	switch(orient) {  
			
		case UIImageOrientationUp: //EXIF = 1  
			transform = CGAffineTransformIdentity;  
			break;  
			
		case UIImageOrientationUpMirrored: //EXIF = 2  
			transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);  
			transform = CGAffineTransformScale(transform, -1.0, 1.0);  
			break;  
			
		case UIImageOrientationDown: //EXIF = 3  
			transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);  
			transform = CGAffineTransformRotate(transform, M_PI);  
			break;  
			
		case UIImageOrientationDownMirrored: //EXIF = 4  
			transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);  
			transform = CGAffineTransformScale(transform, 1.0, -1.0);  
			break;  
			
		case UIImageOrientationLeftMirrored: //EXIF = 5  
			boundHeight = bounds.size.height;  
			bounds.size.height = bounds.size.width;  
			bounds.size.width = boundHeight;  
			transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);  
			transform = CGAffineTransformScale(transform, -1.0, 1.0);  
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);  
			break;  
			
		case UIImageOrientationLeft: //EXIF = 6  
			boundHeight = bounds.size.height;  
			bounds.size.height = bounds.size.width;  
			bounds.size.width = boundHeight;  
			transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);  
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);  
			break;  
			
		case UIImageOrientationRightMirrored: //EXIF = 7  
			boundHeight = bounds.size.height;  
			bounds.size.height = bounds.size.width;  
			bounds.size.width = boundHeight;  
			transform = CGAffineTransformMakeScale(-1.0, 1.0);  
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);  
			break;  
			
		case UIImageOrientationRight: //EXIF = 8  
			boundHeight = bounds.size.height;  
			bounds.size.height = bounds.size.width;  
			bounds.size.width = boundHeight;  
			transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);  
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);  
			break;  
			
		default:  
			[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];  
			
	}  
	
	UIGraphicsBeginImageContext(bounds.size);  
	
	CGContextRef context = UIGraphicsGetCurrentContext();  
	
	if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {  
		CGContextScaleCTM(context, -scaleRatio, scaleRatio);  
		CGContextTranslateCTM(context, -height, 0);  
	}  
	else {  
		CGContextScaleCTM(context, scaleRatio, -scaleRatio);  
		CGContextTranslateCTM(context, 0, -height);  
	}  
	
	CGContextConcatCTM(context, transform);  
	
	CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);  
	UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();  
	UIGraphicsEndImageContext();  
	
	return imageCopy;  
}

+ (UIImage*)imageWithURL:(NSURL*)url {
	return [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}

/**
 * Returns fully-qualified URL.
 */
+ (NSString*)resolveURL:(NSString*)urlString {
	NSRange slashRange = [urlString rangeOfString:@"/"];
	//
	// If this starts with a '/', add the http, etc.
	//
	if (slashRange.location == 0) {
		return [@"http://Criteria.com" stringByAppendingString:urlString];
	} else {
		return urlString;
	}
}

/**
 * Returns a newly-resolved URL.
 */
+ (NSURL*)URLWithString:(NSString*)urlString {
	return [NSURL URLWithString:[Util resolveURL:urlString]];
}

//
// http://mesh.typepad.com/blog/2007/10/url-encoding-wi.html
//
//RFC 3986
//http://tools.ietf.org/html/rfc3986
+(NSString *) urlencode: (NSString *) url
{
	NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
													@"@" , @"&" , @"=" , @"+" ,
													@"$" , @"," , @"[" , @"]",
													@"#", @"!", @"'", @"(", 
													@")", @"*", nil];
	
	NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F" , @"%3F" ,
													 @"%3A" , @"%40" , @"%26" ,
													 @"%3D" , @"%2B" , @"%24" ,
													 @"%2C" , @"%5B" , @"%5D", 
													 @"%23", @"%21", @"%27",
													 @"%28", @"%29", @"%2A", nil];
	
	int len = [escapeChars count];
	
	NSMutableString *temp = [url mutableCopy];
	
	int i;
	for(i = 0; i < len; i++)
	{
		
		[temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i]
													withString:[replaceChars objectAtIndex:i]
														 options:NSLiteralSearch
															 range:NSMakeRange(0, [temp length])];
	}
	
	NSString *out = [NSString stringWithString: temp];
	
	return out;
}

+ (NSString*) formatCurrency:(float)v {
	return [NSString stringWithFormat:@"$%.2f", v];
}

@end
